﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using command;
using Model;
using Newtonsoft.Json;

namespace LXService1
{
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer timer1;  //定义计时器 
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new System.Timers.Timer(1000 * 59);//1000=1秒
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.AutoReset = true;//到达时间的时候执行事件； 
            timer1.Enabled = true;//设置是执行一次（false）还是一直执行(true); 
        }

        protected override void OnStop()
        {
        }
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                Thread taskerTimerThread1 = new Thread(GetLXData);
                taskerTimerThread1.Start();
            }
            catch (Exception ex)
            {
                this.EventLog.WriteEntry("发生意外错误，错误内容4：" + ex.ToString());
            }
        }

        public void GetLXData()
        {
            if (DateTime.Now.Minute == 15 || DateTime.Now.Minute == 30 || DateTime.Now.Minute == 45 || DateTime.Now.Minute == 59)
            {
                try
                {
                    //HttpClient Client = new HttpClient();
                    Log.SaveNote("日志开始 " + DateTime.Now);

                    List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                    List<string> listurl = new List<string>();

                    var headers = new Dictionary<string, string>
                    {
                       { "Authorization", "FN6/jhuULbmg3IFolczTsNI6XpWJeRPeiKQYDe3kCzR6WBVC6KwsJTAnkJHeBmouwMQDxgd0pgpU7/qUgYHZQA==" }
                    };
                    var headers1 = new Dictionary<string, string>
                    {
                       { "Authorization", "a1FX77Et8yPDUBzdElQ7iOU47EFmJG25JNKISyrgePPMkBVoKNEV2mqBntc4i5U1uwIK87aQzW8aKWgFjsYw5A==" }
                    };
                    list.Add(headers);
                    list.Add(headers1);

                    string reportUrl = "http://192.168.22.250:10010/create-virtual-data/details";
                    string reportUrl1 = "http://192.168.22.248:10010/create-virtual-data/details";

                    listurl.Add(reportUrl);
                    listurl.Add(reportUrl1);


                    //JsonSerializerSettings settings = new JsonSerializerSettings
                    //{
                    //    NullValueHandling = NullValueHandling.Ignore,
                    //    DefaultValueHandling = DefaultValueHandling.Ignore
                    //};

                    //Maticsoft.BLL.TypeValue bllValue = new Maticsoft.BLL.TypeValue();
                    for (int ii = 0; ii < list.Count; ii++)
                    {



                        Rootdr1 paramsObject = new Rootdr1
                        {
                            date = DateTime.Today.AddDays(-0).ToString("yyyy-MM-dd"),

                        };

                        string createRetJson = HttpClientUtils.DoJsonPost(paramsObject, listurl[ii], list[ii]);





                        Root1 data = JsonConvert.DeserializeObject<Root1>(createRetJson);//JSON 转成实体

                        if (data.code == 0 && data.result != null)
                        {


                            //Maticsoft.Model.TypeValue data1 = new Maticsoft.Model.TypeValue();

                            Maticsoft.BLL.QFQCType bllType = new Maticsoft.BLL.QFQCType();
                            Maticsoft.BLL.QFQCson bll = new Maticsoft.BLL.QFQCson();
                            DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(data.result.lastTime);
                            DateTime localDateTime = dateTimeOffset.LocalDateTime;
                            int count = bll.Delete("  FS08 ='" + data.result.line + "'  and FS09 ='" + data.result.customer + "' and FS10='" + data.result.model + "'  AND  MODT ='" + Convert.ToDateTime(localDateTime).Date + "'  ");

                            Maticsoft.Model.QFQCson QFQCson = new Maticsoft.Model.QFQCson();
                            PropertyInfo[] properties = data.result.defictive.GetType().GetProperties();

                            for (int i = 0; i < properties.Length; i++)
                            {
                                QFQCson = new Maticsoft.Model.QFQCson();
                                string propertyName = properties[i].Name; // 如 "PIN低", "PIN高"
                                object propertyValue = properties[i].GetValue(data.result.defictive);


                                QFQCson.CRT = Convert.ToDateTime(localDateTime);

                                QFQCson.CRP = "自动化采集";
                                QFQCson.MODT = QFQCson.CRT.Date;

                                QFQCson.FS02 = propertyName;
                                QFQCson.FS03 = Convert.ToInt32(propertyValue);
                                QFQCson.FS08 = data.result.line;
                                QFQCson.FS09 = data.result.customer;
                                QFQCson.FS10 = data.result.model;

                                QFQCson.FS20 = data.result.totalplan; //计划总数据
                                QFQCson.FS13 = data.result.leader; //组长
                                QFQCson.FS21 = data.result.totalresidue; //剩余完成量


                                var type = bllType.GetList(" name ='" + propertyName + "' ");

                                if (type.Tables[0].Rows.Count != 0)
                                {
                                    QFQCson.FS07 = type.Tables[0].Rows[0]["Value"].ToString();

                                }
                                else
                                {
                                    QFQCson.FS07 = "其它";
                                }
                                if (propertyName == "加工数")
                                {
                                    QFQCson.FS12 = Convert.ToInt32(propertyValue);
                                    QFQCson.FS07 = "生产总数";

                                }
                                int iii = bll.Add(QFQCson);
                            }

                            //string aaa = DateTime.Now.AddDays(-0).ToString("yyyy-MM-dd");
                            //bool ii = bll.Delete(aaa, item);
                            //bool delete = bllValue.Delete1(aaa, item);


                            //listfrontend.accumulateVolume = Convert.ToDecimal(data.results[0].accumulateVolume);
                            //listfrontend.electricityCosume = Convert.ToDecimal(data.results[0].electricityCosume);
                            //listfrontend.code = data.code;
                            //listfrontend.message = data.message;
                            //listfrontend.stationNumber = data.pager.stationNumber;
                            //listfrontend.timestamp = data.results[0].timestamp;
                            //long timestamp = data.results[0].timestamp;
                            //DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
                            //DateTime localDateTime = dateTimeOffset.LocalDateTime;
                            //listfrontend.displayTime = Convert.ToDateTime(localDateTime);
                            //listfrontend.count = data.results[0].count;
                            //listfrontend.vendor = data.results[0].vendor;
                            //listfrontend.bitPart = data.results[0].bitPart;
                            //listfrontend.deviceId = data.results[0].deviceId;
                            //listfrontend.valueMapping = data.results[0].valueMapping.ToJSON();

                            // data1 = JsonConvert.DeserializeObject<Maticsoft.Model.TypeValue>(listfrontend.valueMapping, settings);

                            //data1.count = listfrontend.count;
                            //data1.deviceId = listfrontend.deviceId;
                            //data1.displayTime = listfrontend.displayTime;
                            //data1.stationNumber = listfrontend.stationNumber;
                            //data1.timestamp = listfrontend.timestamp;
                            //int i = bll.Add(listfrontend);
                            //bllValue.Add(data1);
                        }
                    }


                }
                catch (Exception ex)
                {
                    Log.SaveNote("错误" + ex.ToString() + DateTime.Now);
                }
            }
        }
        public class Rootdr1
        {
            /// <summary>
            /// 当前分页页数
            /// </summary>
            public string date { get; set; }

        }
    }
}
